Functions

-- method 1
local function hello(name)
    print('hello', name)
end

-- method 2  (preferred)
local greet = function(name)
    print('hello ' .. name)
end

Multiple returns

local returns_four_values = function()
  return 1, 2, 3, 4
end

first, second, last = returns_four_values()

print("first: ", first)
print("second:", second)
print("last:  ", last)
-- the `4` is discarded

Variadic Parameters

  • Using ...

local variable_arguments = function(...)
  local arguments = { ... }
  for i, v in ipairs({...}) do print(i, v) end
  return unpack(arguments)
end

print("===================")
print("1:", variable_arguments("hello", "world", "!"))
print("===================")
print("2:", variable_arguments("hello", "world", "!"), "<lost>")

Convention

  • Functions usually accept 1 Table as a parameter, where inside that table you pass names like default , other , etc.

local setup = function(opts)
  if opts.default == nil then
    opts.default = 17
  end

  print(opts.default, opts.other)
end

setup { default = 12, other = false}
setup { other = true}

OOP

local MyTable = {}

-- These are equivalent
function MyTable.something(self, ...) end
function MyTable:something(...) end
    -- "This is syntax sugar for `.` and `self`.